export default {
	// 开启命名空间
	namespaced: true,
	state: () => ({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		ADDTOCART(state,val) {
			const res = state.cart.find(x => x.goods_id === val.goods_id)
			if (!res) {
				state.cart.push(val)
				uni.$showMsg('加入购物车成功!')
			} else {
				res.goods_count += 1
				uni.$showMsg('商品数量加1!')
			}
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		REFRESHCOUNT(state,val) {
			const res = state.cart.find(x => x.goods_id === val.goods_id)
			if (res) {
				res.goods_count = val.goods_count
			}
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		DELGOODS(state,val) {
			state.cart = state.cart.filter(x => x.goods_id !== val.goods_id)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		total(state) {
			let num = 0
			state.cart.forEach(val => num += val.goods_count) 
			return num
		}
	}
}